package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"os"
	"os/signal"
	"server/base"
	"server/base/db"
	"server/base/redis"
	"server/service"
	"server/service/node/method"
	"syscall"
	"time"

	"github.com/gorilla/mux"
)

const (
	VERSION = "0.1.0"
)

var args struct {
	Port     int
	ConfFile string
}

func healthHandler(_ http.ResponseWriter, _ *http.Request) {
}

func init() {
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
	log.SetOutput(os.Stdout)

	flag.IntVar(&args.Port, "port", 8888, "server listening port")
	flag.StringVar(&args.ConfFile, "config", "config.toml", "config file")
	rand.Seed(time.Now().Unix())
}

func main() {
	flag.Parse()

	conf := LoadConfigFile(args.ConfFile)
	redis.Install(conf.Redis)
	if err := db.Install(conf.Mysql); err != nil {
		panic(err)
	}

	listenAddr := fmt.Sprintf("0.0.0.0:%d", args.Port)
	router := mux.NewRouter()
	// 健康检查
	router.HandleFunc("/health", healthHandler)

	service.RegisterMethod(router, "/v1/test", method.Test)
	service.RegisterMethod(router, "/v1/game/list", method.Game_list)
	service.RegisterMethod(router, "/v1/placeorder1", method.PlaceOrder1)
	service.RegisterMethod(router, "/v1/placeorder2", method.PlaceOrder2)
	service.RegisterMethodRaw(router, "/v1/mock.js", method.MockJs)
	service.RegisterMethod(router, "/v1/ask_task", method.AskTask)
	service.RegisterMethod(router, "/v1/fin_task", method.FinTask)
	service.RegisterMethodRaw(router, "/v1/wxlogin", method.WxLogin)
	service.RegisterMethod(router, "/v1/account/info", method.AccountInfo)
	service.RegisterMethod(router, "/v1/account/orderlist", method.AccountOrderlist)
	service.RegisterMethod(router, "/v1/account/ordergames", method.AccountOrdergames)
	service.RegisterMethod(router, "/v1/log/keyword", method.LogKeyword)
	service.RegisterMethod(router, "/v1/order/waitingPkgs", method.Order_waitingPkgs)
	service.RegisterMethodRaw(router, "/v1/order/txt", method.Order_Txt)

	// Interrupt handler.
	errc := make(chan error)
	go func() {
		c := make(chan os.Signal)
		signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
		errc <- fmt.Errorf("%s", <-c)
	}()

	// HTTP transport.
	go func() {
		log.Println("listening:", listenAddr)
		err := http.ListenAndServe(listenAddr, router)
		base.Raise(err)
	}()

	//rows := biz.ReadExcel("./ps4.xlsx")
	//s := base.JsonString(rows)
	//s = "var gametable=" + s + ";"
	//err := ioutil.WriteFile("gametable.js", []byte(s), fs.ModePerm)
	//base.Raise(err)

	// Run!
	log.Println("exit:", <-errc)
}
